//
//  BaseTabBarController.m
//  XV
//
//  Created by apple on 2019/03/11.
//  Copyright © 2019 XV. All rights reserved.
//

#import "BaseTabBarController.h"
#import "UserInfoModel.h"
#import "AppDelegate.h"
#import "UnreadMessageModel.h"


@interface BaseTabBarController ()<UITabBarControllerDelegate>

//未读消息
@property (nonatomic,assign) NSInteger sessionUnreadCount;

@property (nonatomic,assign) NSInteger systemUnreadCount;

@property (nonatomic,assign) NSInteger customSystemUnreadCount;

@end

@implementation BaseTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //self.delegate = self;
    
    //用户在其它设备登录的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleUserInvalidTokenNotification:)
                                                 name:UserInvalidTokenNotification
                                               object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    
    //用户在其它设备登录的通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UserInvalidTokenNotification object:nil];
}

//用户在其它设备登录的通知
- (void)handleUserInvalidTokenNotification:(NSNotification *)notification
{
    // 归档
    [UserInfoModel removeUserInfo];
    
    //登录
    AppDelegate* app = (AppDelegate *) [[UIApplication sharedApplication] delegate];
    [app to_LoginVC];
}




#pragma mark - UITabBarControllerDelegate
//当选中项改变的时候会触发
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    
}

//每次点击当前tab的时候会触发
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    //当前选中的tab
    UIViewController *selectTab = tabBarController.selectedViewController;

    //vc:  将要选中的tab
    //判断是不是选择了自己
    if ([selectTab isEqual:viewController])
    {
        //发送刷新通知
        //[[NSNotificationCenter defaultCenter] postNotificationName:TabBarItemDidSelectedNotification object:self];
    }
    
    return YES;
} 


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //未读消息
    UnreadMessageModel* model = [UnreadMessageModel read:[UserInfoModel getUID]];
    [self showUnreadBadgeValueWithValue:[model getUnreadCount]];
}

- (void)showUnreadBadgeValueWithValue:(NSInteger)value{
    
    UINavigationController *nav = (UINavigationController *)self.viewControllers[2];
    nav.tabBarItem.badgeValue = value==0 ? nil : [NSString stringWithFormat:@"%ld",value];
}

@end
